//index.js
//获取应用实例
const app = getApp()

Page({
    data: {
        bgsrc: "",
        isShowShareId: true, //编辑按钮的是否显示
        avatar: "",
        name: "",
        position: "",
        company: "",
        popularity: "",
        like: "",
        forward: "",
        mobile: "",
        email: "",
        company: "",
        wechar: "",
        staffqr: "",
        phoneNumber: "",
        motto: 'Hello World',
        userInfo: {},
        isShowName:false,
        hasUserInfo: false,
        modalData: {
            isShow: false,
            type: 1,
            isWrite: false
        },

        //全局变量
        // hasUserInfo: app.globalData.hasUserInfo,
        // modalData: app.globalData.isShow,

        canIUse: wx.canIUse('button.open-type.getUserInfo'),
        flag: true,
        shopNumber: "",
        emial: "",
        bgHeader: "",
        show: false,
        hot: "/image/images/hot1.png",
        num: 0,
        userInfos: {
            hotNum: 0,
            goodNum: 0,
            transmit: 0
        },

        getUser: wx.getStorageSync("getUser"),
        header: "",
        isSha: false,
        peopleId: "",
        //分享朋友圈
        height: getApp().globalData.height,
        heightS: getApp().globalData.height * 2,
        balanceHeight: 0,
        CustomBar: getApp().globalData.CustomBar,
        height: wx.getSystemInfoSync().windowHeight,
        sharebg: 'https://dss0.baidu.com/73t1bjeh1BF3odCf/it/u=1722579335,1569699472&fm=85&s=D8927D9546A81EAC572410660300C070', // 分享底部背景图
        shareTitle: '测试员', // 分享标题
        shareCoverImg: 'https://wx.arrowgroup.com.cn/statics/uploads/20200427/163759a7dab5fe3a8f557c595601eb96439d98.png', // 分享封面图
        shareQrImg: 'https://wx.arrowgroup.com.cn/statics/qr/1_20200427f562b12980ec7908d41923fbe2be9c3f.png', // 分享小程序二维码
        title: '',
        isShare: true,
        isImg: true,
        userTop: {
            name: "",
            phone: "",
            email: "",
            // company: "",
            position: "",
            wechart: ""
        },
        username: "",
        userposition: "",
        usermobile: "",
        useremail: "",
        userwechar: ""
    },
    onShow: function () {
        // this.initChange()
        // this.initCanvas()
        //-----------------------------------------------------------------

    },
    initCanvas: function () {
        let that = this;
        // wx.setNavigationBarTitle({
        //     title: '分享到朋友圈',
        // })
        const ctx = wx.createCanvasContext('shareCanvas') //获取画布id
        // 白色背景
        ctx.setFillStyle('#ffffff')
        ctx.fillRect(0, 120, 500, 1000) // 画布（x,y.width,heigh）
        ctx.setFillStyle('#000') // 文字颜色：黑色
        ctx.setFontSize(30) // 文字字号：20px
        const title = that.data.title;
        const fontWidth = ctx.measureText(title).width
        // console.log(fontWidth);
        const getwith = (345 - fontWidth) * 0.5;
        // console.log(getwith);
        ctx.fillText(title, getwith, 30)
        ctx.draw()
        // console.log(res)
        //开始画图
        wx.getImageInfo({
            src: that.data.staffqr,
            success: (res1) => {
                ctx.drawImage(res1.path, 122.5, 370, 110, 110) //这是底部二维码的位置
                // 下载视频封面图
                wx.getImageInfo({
                    src: that.data.poster,
                    success: (res2) => {
                        ctx.drawImage(res2.path, 0, 0, 345, 200) //这是背景的位置
                        // 分享标题
                        // ctx.setTextAlign('center')    // 文字居中
                        ctx.setFillStyle('#686465') // 文字颜色：黑色
                        ctx.setFontSize(16) // 文字字号：20px
                        if (that.data.shareTitle.length <= 21) {
                            // 不用换行
                            ctx.setFontSize(17) // 文字字号：20px
                            ctx.fillText(that.data.name, 30, 250) //名字
                            ctx.fillText(that.data.position, 130, 250) //职位
                            ctx.fillText(that.data.company, 210, 250) //公司
                            ctx.fillText("手机:  " + that.data.mobile, 30, 290) //手机
                            ctx.fillText("邮箱:  " + that.data.email, 30, 320) //邮箱
                            ctx.fillText("微信:  " + that.data.wechar, 30, 350) //微信
                        }
                        // 下载二维码
                        wx.getImageInfo({
                            src: that.data.shareQrImg,
                            success: (res3) => {
                                let qrImgSize = 70
                                ctx.stroke()
                                ctx.draw(true)
                            }
                        })
                    }
                })
            }
        })
    },

    //---------------------------------------------------
    shareFriend: function () {
        wx.canvasToTempFilePath({
            canvasId: 'shareCanvas',
            success: function (res) {
                wx.saveImageToPhotosAlbum({
                    filePath: res.tempFilePath,
                    success: function (res) {
                        wx.showToast({
                            title: '分享图片已保存到相册,请到朋友圈选择图片发布'
                        })
                    }
                })
            }
        }, this)
    },
    closeShare: function () {
        this.setData({
            isSha: false
        })
    },
    //---------------------------------------------------------------

    getUserLogo: function () {
        console.log('数据的地方')
        app.globalData.call.authApi("getStaffInfo").then(res => {
            if (res.code == 200) {
                this.setData({
                    name: res.data.name,
                    poster: res.data.poster,
                    like: res.data.like,
                    popularity: res.data.popularity,
                    forward: res.data.forward,
                    avatar: res.data.avatar,
                    position: res.data.position,
                    company: res.data.company,
                    mobile: res.data.mobile,
                    email: res.data.email,
                    company: res.data.company,
                    peopleId: res.data.id,
                    staffqr: res.data.staffqr,
                    wechar: res.data.wechar
                })

            }

            // console.log(res,"getUserLogogetUserLogogetUserLogo")

        })
    },
    initData: function () {
        this.phoneNumber()
    },
    initChange: function () {
        app.globalData.call.authApi("getStaffInfo", {
            token: wx.getStorageSync('token'),
        }).then(res => {
            // console.log(res)
            this.setData({
                header: res.data.avatar
            })
        })
    },
    getUserLike: function () {
        app.globalData.call.authApi("getLike", {
            // site_id: wx.getStorageSync("userId")
            token: wx.getStorageSync("token"),
            id: wx.getStorageSync("userId")
        }).then(res => {
            // console.log("Ppppppppppppppppp")
            // this.setData({
            //     // like: res.data.like,
            //     popularity: res.data.popularity,
            //     forward: res.data.forward
            // })
        })
    },

    // phoneNumber: function(e) {
    //     if (e.detail.errMsg == "getPhoneNumber:fail user deny") {
    //         return false;
    //     }
    //     wx.login({
    //         success: res => {
    //             // console.log(res, "------------------");
    //             wx.showLoading({
    //                 title: '加载中',
    //                 icon: 'loading'
    //             });
    //             app.globalData.call.authApi('getUserPhone', {
    //                 code: res.code,
    //                 encryptedData: e.detail.encryptedData,
    //                 iv: e.detail.iv,
    //             }).then(data => {
    //                 console.log(data, '-----------------返回手机号码')
    //                 wx.setStorageSync("userPhone", data.data.phoneNumber)
    //                 app.globalData.call.authApi("getStaffInfo", {
    //                     token: wx.getStorageSync('token'),
    //                     mobile: data.data.phoneNumber,
    //                 }).then(resp => {
    //                     // console.log()
    //                     if (resp.code == 0) {
    //                         wx.showToast({
    //                             title: "您没有权限"
    //                         })
    //                     } else {
    //                         console.log(resp.data.poster, "----------------------------")
    //                         this.setData({
    //                             name: resp.data.name,
    //                             poster: resp.data.poster,
    //                             like: resp.data.like,
    //                             popularity: resp.data.popularity,
    //                             forward: resp.data.forward,
    //                             avatar: resp.data.avatar,
    //                             position: resp.data.position,
    //                             company: resp.data.company,
    //                             mobile: resp.data.mobile,
    //                             email: resp.data.email,
    //                             company: resp.data.company,
    //                             peopleId: resp.data.id,
    //                             staffqr: resp.data.staffqr,
    //                             wechar: resp.data.wechar
    //                         })
    //                         wx.setStorageSync("getUser", resp)
    //                         // wx.setStorageSync("popularity", resp.data.popularity)
    //                         // wx.setStorageSync("like", resp.data.like)
    //                         // wx.setStorageSync("forward", resp.data.forward)
    //                         // wx.setStorageSync("userId", resp.data.id)
    //                         bgHeader: wx.getStorageSync("bgHeader").data.poster
    //                         // console.log(this.data.getUser,"this.getUser")
    //                     }

    //                 })
    //                 this.setData({
    //                     phoneNumber: data.data.phoneNumber,
    //                     modalData: {
    //                         isShow: false
    //                     }
    //                 });
    //                 wx.hideLoading();
    //             });
    //         }
    //     });
    // },

    compony: function () {
        app.globalData.call.api("getCompony").then(res => {
            if (res.code == 200) {
                this.setData({
                    bgsrc: res.data.background
                })
            }
        })
    },


    getphonenumber: function (e) {
        this.setData({
            phoneNumber: e.detail.value
        })
    },

    /**
     * 弹出层函数
     */
    //出现
    clickCode: function () {
        var site_id = this.data.peopleId
        var mobile = wx.getStorageSync("userPhone")
        // console.log(mobile)
        if (this.data.sharid) {
            app.globalData.call.api("getStaffInfoshare", { id: this.data.sharid }).then(res => {
                if (res.code == 200) {
                    this.setData({
                        poster: res.data.poster
                    })
                }
            })
        } else {
            app.globalData.call.authApi("createQr", {
                site_id: site_id
            }).then(res => {
                if(res.code == 200){
                   this.setData({
                       staffqr:res.data
                   }) 
                }
            })
            app.globalData.call.authApi("getStaffInfo").then(res => {
                if (res.code == 200) {
                    this.setData({
                        poster: res.data.poster
                    })
                }
            })
        }
        this.setData({
            flag: false
        })
    },
    close: function () {
        this.clickCodes()
    },
    clickCodes: function () {
        this.setData({
            flag: true
        })
    },

    click: function () {
        var like = this.data.like;
        var id = this.data.peopleId
        if (this.data.show) {
            app.globalData.call.authApi("getLike", {
                token: wx.getStorageSync("token"),
                id: id,
                type: '0'
            }).then(res => {
                this.setData({
                    show: false,
                    like: res.data.like
                })
                wx.setStorageSync("like", res.data.like)
            })
        } else {
            app.globalData.call.authApi("getLike", {
                token: wx.getStorageSync("token"),
                id: id,
                type: '1'
            }).then(res => {
                this.setData({
                    show: true,
                    like: res.data.like
                })
                wx.setStorageSync("like", res.data.like)
            })
        }
    },
    //消失
    hide: function () {
        // console.log(123)
        this.setData({
            flag: false
        })
    },
    //事件处理函数
    upload() {
        let that = this;
        wx.chooseImage({
            count: 1,
            sizeType: ['original', 'compressed'],
            sourceType: ['album', 'camera'],
            success(ret) {
                // console.log(ret)
                wx.showLoading({
                    title: '上传中',
                })
                wx.uploadFile({
                    url: 'https://wx.arrowgroup.com.cn/upload', //仅为示例，非真实的接口地址
                    filePath: ret.tempFilePaths[0],
                    name: 'file',
                    success: function (res) {
                        // console.log(,"================")
                        let token = wx.getStorageSync("token")
                        let filename = JSON.parse(res.data).filename
                        // let id = wx.getStorageSync('userId')
                        var peopleId = that.data.peopleId
                        wx.hideLoading()
                        app.globalData.call.authApi('Upback', {
                            filename,
                            id: peopleId
                        }).then(res => {
                            // console.log(res,"//////////////")
                            that.setData({
                                poster: res.data
                            })
                        })

                    }
                })
            }
        })
    },

    sonCode: function (e) {
        let num = e.currentTarget.dataset.num
        if (num == 1) {
            // console.log(1111)
            app.globalData.call.authApi("createQr", {
                site_id: this.data.peopleId
            }).then(res => {
                // console.log(res,"=================")
                wx.downloadFile({
                    url: res.data,
                    //需要下载的图片url
                    success: function (ress) {　　　　　　　　　　　　 //成功后的回调函数
                        wx.saveImageToPhotosAlbum({　　　　　　　　　 //保存到本地
                            filePath: ress.tempFilePath,
                            success(res) {
                                wx.showToast({
                                    title: '保存成功',
                                    icon: 'success',
                                    duration: 2000
                                })
                            },
                        })
                    }
                });
            })
        } else if (num == 2) {
            // console.log("222222222222")
            this.setData({
                isSha: true
            })
            this.shareFriend()
            this.initCanvas()
        }
    },
    callPhone: function () {
        let phoneNumber = this.data.mobile
        // let getUser = wx.getStorageSync("getUser")
        wx.makePhoneCall({
            phoneNumber: phoneNumber,
            success: function () {
                // console.log('拨打成功')
            },
            fail: function () {
                // console.log('拨打失败')
            }
        })
    },
    bindViewTap: function () {
        wx.navigateTo({
            url: '../logs/logs'
        })
    },
    showModal(e) {
        // console.log(e)
        this.setData({
            modalName: e.currentTarget.dataset.target
        })
    },
    hideModal(e) {
        this.setData({
            modalName: null
        })
    },
    isSuer() {
        var that = this;
        var username = that.data.username;
        var userposition = that.data.userposition;
        var usermobile = that.data.usermobile;
        var useremail = that.data.useremail;
        var userwechar = that.data.userwechar;
        let userTop = this.data.userTop

        if (username.length == 0 || username == undefined || username == '') {
            wx.showToast({
                title: '姓名不能为空',
                icon: 'none'
            })
        } else if (userposition.length == 0 || userposition == undefined || userposition == '') {
            wx.showToast({
                title: '职位不能为空',
                icon: 'none'
            })
        } else if (usermobile.length == 0 || usermobile == undefined || usermobile == '') {
            wx.showToast({
                title: '手机不能为空',
                icon: 'none'
            })
        } else {
            app.globalData.call.authApi('setStaffInfo', {
                token: wx.getStorageSync('token'),
                name: username,
                mobile: usermobile,
                email: useremail,
                position: userposition,
                wechar: userwechar
            }).then(res => {
                console.log('修改成功')
                this.hideModal()
                this.getUserLogo()
            })
        }


    },
    bindInput: function (e) {
        var username = e.detail.value;
        if (username == undefined || username.length == 0 || username == '') {
            wx.showToast({
                title: '请输入姓名',
            })
        } else {
            this.setData({
                username: username
            })
        }
    },
    bindInput2: function (e) {
        var userposition = e.detail.value;
        if (userposition == undefined || userposition.length == 0 || userposition == '') {
            wx.showToast({
                title: '请输职位',
            })
        } else {
            this.setData({
                userposition: userposition
            })
        }
    },
    bindInput3: function (e) {
        var usermobile = e.detail.value;
        if (usermobile == undefined || usermobile.length == 0 || usermobile == '') {
            wx.showToast({
                title: '请输入手机',
            })
        } else {
            this.setData({
                usermobile: usermobile
            })
        }
    },
    bindInput4: function (e) {
        var useremail = e.detail.value;
        if (useremail == undefined || useremail.length == 0 || useremail == '') {
            wx.showToast({
                title: '请输入邮箱',
            })
        } else {
            this.setData({
                useremail: useremail
            })
        }
    },
    bindInput5: function (e) {
        var userwechar = e.detail.value;
        if (userwechar == undefined || userwechar.length == 0 || userwechar == '') {
            wx.showToast({
                title: '请输入微信号',
            })
        } else {
            this.setData({
                userwechar: userwechar
            })
        }
    },
    // initChange:function(){

    // },
    /**
     * 用户点击右上角分享,获取按钮触发的分享
     */
    onShareAppMessage: function (e) {
        console.log(e)
        let token = wx.getStorageSync("token")
        let sharid = this.data.peopleId
        console.log(sharid)
        var isShares = 'y';
        var avatar = this.data.avatar;
        if (e.from === 'button') {
            // console.log(id)
            app.globalData.call.authApi('getForward', {
                token,
                id: sharid
            }).then(res => {
                // console.log('转发成功')
            })
            return {
                title: "箭牌家居集团",
                path: 'pages/index/index?sharid=' + sharid + '&isShares=' + isShares + '&avatar=' + avatar, // 分享出去是 1 
                success: function (res) {
                    // 转发成功
                    // console.log("转发成功:" + res);

                },
                fail: function (res) {
                    // 转发失败
                    // console.log("转发失败:" + JSON.stringify(res));
                }
            }
        } else if (e.from === "menu") {
            app.globalData.call.authApi('getForward', {
                token,
                id: sharid
            }).then(res => {
                // console.log('转发成功')
            })
            return {
                title: "箭牌家居集团",
                path: 'pages/index/index?sharid=' + sharid + '&isShares=' + isShares + '&avatar=' + avatar, // 分享出去是 1 
                success: function (res) {
                    // 转发成功
                    console.log("转发成功:" + res);
                },
                fail: function (res) {
                    // 转发失败
                    console.log("转发失败:" + JSON.stringify(res));
                }
            }
        }
    },
    onLoad: function (options) {
        if (options.scene){
            console.log(options, '数据是佛整齐')
            if (options.sharid) {
                this.setData({
                    isShowShareId: false,
                    sharid: options.sharid,
                    avatar: options.avatar
                })
            }
            app.globalData.call.api("getStaffShare", {
                id: options.sharid
            }).then(res => {
                if (res.code == 200) {
                    this.compony()
                    console.log(res, "-*************isSharesisSharesisShares**")
                    this.setData({
                        getUser: res,
                        name: res.data.name,
                        poster: res.data.poster,
                        forward: res.data.forward,
                        position: res.data.position,
                        mobile: res.data.mobile,
                        email: res.data.email,
                        company: res.data.company,
                        peopleId: res.data.id,
                        staffqr: res.data.staffqr,
                        wechar: res.data.wechar,
                        hasUserInfo: true,
                        // avatar: res.data.avatar,
                        popularity: res.data.popularity,
                        like: res.data.like,
                        modalData: {
                            isShow: false
                        },
                        isImg: false
                    })
                    wx.setStorageSync('getUser', res)
                    // let getUser = wx.getStorageSync('getUser')
                    let poster = wx.getStorageInfoSync('getUser').data.poster
                    let staffqr = wx.getStorageInfoSync('getUser').data.staffqr
                    let getUser = wx.getStorageSync('getUser')
                    this.setData({
                        poster: getUser.data.poster
                    })
                    this.initCanvas()
                    wx.clearStorage()
                    // console.log(getUser, "分享成功")
                }

            })
        }
        //如果是分享进来，判断是否为1 ，1：被分享者进来的请求接口
        if (options.isShares == 'y') {
            console.log(options, '数据是佛整齐')
            if (options.sharid) {
                this.setData({
                    isShowShareId: false,
                    sharid: options.sharid,
                    avatar:options.avatar
                })
            }
            app.globalData.call.api("getStaffShare", {
                id: options.sharid
            }).then(res => {
                if (res.code == 200) {
                    this.compony()
                    console.log(res, "-*************isSharesisSharesisShares**")
                    this.setData({
                        getUser: res,
                        name: res.data.name,
                        poster: res.data.poster,
                        forward: res.data.forward,
                        position: res.data.position,
                        mobile: res.data.mobile,
                        email: res.data.email,
                        company: res.data.company,
                        peopleId: res.data.id,
                        staffqr: res.data.staffqr,
                        wechar: res.data.wechar,
                        hasUserInfo: true,
                        // avatar: res.data.avatar,
                        popularity: res.data.popularity,
                        like: res.data.like,
                        modalData: {
                            isShow: false
                        },
                        isImg: false
                    })
                    wx.setStorageSync('getUser', res)
                    // let getUser = wx.getStorageSync('getUser')
                    let poster = wx.getStorageInfoSync('getUser').data.poster
                    let staffqr = wx.getStorageInfoSync('getUser').data.staffqr
                    let getUser = wx.getStorageSync('getUser')
                    this.setData({
                        poster: getUser.data.poster
                    })
                    this.initCanvas()
                    wx.clearStorage()
                    // console.log(getUser, "分享成功")
                }

            })
        } else {
            // this.setData({
            //     loginStatus: app.globalData.loginStatus
            // })
            if (app.globalData.loginStatus) {
                this.getUserLogo();
                this.compony()
                if (app.globalData.userInfo) {
                    this.setData({
                        userInfo: app.globalData.userInfo,
                        hasUserInfo: true
                    })
                } else if (this.data.canIUse) {
                    // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
                    // 所以此处加入 callback 以防止这种情况
                    app.userInfoReadyCallback = res => {
                        this.setData({
                            userInfo: res.userInfo,
                            hasUserInfo: true
                        })
                    }
                } else {
                    // 在没有 open-type=getUserInfo 版本的兼容处理
                    wx.getUserInfo({
                        success: res => {
                            app.globalData.userInfo = res.userInfo
                            this.setData({
                                userInfo: res.userInfo,
                                hasUserInfo: true
                            })
                        }
                    })
                }
            } else {
                this.compony();
            }
            // const token = wx.getStorageSync("token")

            // if (token) {
            //     this.getUserLogo()
            // }
            // if (app.globalData.loginStatus) {
            //     if (app.globalData.userInfo.hasOwnProperty('nickName')) {
            //         this.setData({
            //             userInfo: app.globalData.userInfo,
            //             hasUserInfo: true
            //         })
            //     }
            // } else if (this.data.canIUse) {
            //     // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
            //     // 所以此处加入 callback 以防止这种情况
            //     app.userInfoReadyCallback = res => {
            //         this.setData({
            //             userInfo: res.userInfo,
            //             hasUserInfo: true
            //         })
            //     }
            // } else {
            //     // 在没有 open-type=getUserInfo 版本的兼容处理
            //     wx.getUserInfo({
            //         success: res => {
            //             app.globalData.userInfo = res.userInfo
            //             this.setData({
            //                 userInfo: res.userInfo,
            //                 hasUserInfo: true
            //             })
            //         }
            //     })
            // }
        }
    },
    getUserinfo(e) {
        if (app.globalData.loginStatus) {
            // console.log('has login');
        } else {
            if (e.detail.userInfo) {
                wx.login({
                    success: res => {
                        // console.log(res);
                        wx.showLoading({
                            title: '登录中...'
                        });
                        let code = res.code
                        let encryptedData = e.detail.encryptedData
                        let iv = e.detail.iv
                        app.globalData.call.api('weappLogin', {
                            code,
                            encryptedData,
                            iv,
                        }).then(data => {
                            // this.setData({
                            //     avatar: data.user.avatar
                            // })
                            console.log(data, "11111111111")
                            wx.setStorageSync('token', data.token)
                            wx.hideLoading();
                            if (data.code === 200) {
                                //登录成功
                                this.compony();
                                app.globalData.call.authApi("getStaffInfo").then                                        (res => {
                                    if (res.code == 0) {
                                        console.log(res.code, '陈宫')
                                        var modalName = 'Modal'
                                        this.setData({
                                            modalName: modalName
                                        })
                                    }
                                    wx.showToast({
                                        title: data.message
                                    });
                                    this.setData({
                                        userInfo: data.userInfo,
                                        hasUserInfo: true,
                                        name: res.data.name,
                                        poster: res.data.poster,
                                        like: res.data.like,
                                        popularity: res.data.popularity,
                                        forward: res.data.forward,
                                        avatar: res.data.avatar,
                                        position: res.data.position,
                                        company: res.data.company,
                                        mobile: res.data.mobile,
                                        email: res.data.email,
                                        company: res.data.company,
                                        peopleId: res.data.id,
                                        staffqr: res.data.staffqr,
                                        wechar: res.data.wechar
                                    });
                                    wx.setStorageSync('token', data.token);
                                    wx.setStorageSync('userInfo', data.userInfo);
                                })
                            } else {
                                //登录失败
                                wx.showToast({
                                    title: data.message,
                                    icon: 'loading'
                                })
                            }
                        });
                    }
                })
            } else {
                //拒绝授权
                wx.showToast({
                    icon: 'none',
                    title: '用户拒绝授权'
                })
            }
        }
    },

})